package sgd.tp2.api.cdr;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public final class CDRHandlerXML implements ICDRHandler {

	public static String getXMLFromCDR(CDR cdr) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(CDR.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		
		StringWriter strWriter = new StringWriter();
		marshaller.marshal(cdr, strWriter);
		
		return strWriter.toString();
	}
	
	public static CDR getCDRFromXML(String xml) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(CDR.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		StringBuffer xmlStrBuf = new StringBuffer(xml);
		
		return (CDR)unmarshaller.unmarshal(new StreamSource(new StringReader(xmlStrBuf.toString())));
	}
}
